package com.mls.guardian.executor.master;

import com.mls.guardian.common.RemoteUtil;
import com.mls.guardian.container.MasterContainer;
import com.mls.guardian.dataobj.BackupProjectObj;
import com.mls.guardian.dataobj.BackupServerObj;
import com.mls.guardian.dataobj.ServerInfo;
import com.mls.guardian.protocol.RemoteBody;
import com.mls.guardian.protocol.RemoteCommand;
import com.mls.guardian.protocol.body.AppRestartBody;
import com.mls.guardian.protocol.body.BackupInfoBody;
import com.mls.guardian.protocol.body.ServerInfoBody;
import com.mls.guardian.remoting.executor.RemoteExecutor;
import com.mls.guardian.remoting.netty.RemoteTools;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by pengrenfang on 15/11/11.
 */
public class GetBackupExecutor implements RemoteExecutor {

    private static final Logger log = LoggerFactory.getLogger(GetBackupExecutor.class);
    private MasterContainer container;

    public GetBackupExecutor(MasterContainer container) {
        this.container = container;
    }

    @Override
    public RemoteBody execute(ChannelHandlerContext ctx, RemoteCommand request) throws Exception {
        BackupInfoBody response = new BackupInfoBody();
        List<BackupServerObj> backupServerObjList = new ArrayList<BackupServerObj>();


        //master
        BackupInfoBody requstBody = (BackupInfoBody) request.getRemoteBody();
        BackupServerObj backupServerObj = new BackupServerObj();
        backupServerObj.setIp(RemoteUtil.getLocalHostIP());
        backupServerObj.setRole("MASTER");
        backupServerObj.setList(container.getAppController().getBackup(requstBody.getProjectName(), requstBody.getVersionTag()));
        backupServerObjList.add(backupServerObj);


        //slave
        Map clients = container.getClientDispatch().getClient();
        List<String> listAddr = new ArrayList<String>();
        Iterator iterator = clients.keySet().iterator();
        while (iterator.hasNext()) {
            listAddr.add((String) iterator.next());
        }

        List<RemoteBody> remoteBodyList = container.getClientDispatch().sendRequestToClients(request, listAddr, -1);
        for (int i = 0; i < remoteBodyList.size(); i++) {
            BackupInfoBody body = (BackupInfoBody) remoteBodyList.get(i);

            BackupServerObj info = new BackupServerObj();
            info.setIp(listAddr.get(i));
            info.setRole("SLAVE");
            info.setList(body.getBackupServerObjList().get(0).getList());
            backupServerObjList.add(info);
        }

        response.setProjectName(requstBody.getProjectName());
        response.setVersionTag(requstBody.getVersionTag());
        response.setBackupServerObjList(backupServerObjList);

        return response;
    }
}
